#!/usr/bin/env bash

source ./config/env.sh
clear

mkdir -p ${K8S_DATA}/config/keepalived

masterIP=`echo ${MASTER_IP} | cut -d " " -f 1`

cat  > ${K8S_DATA}/config/keepalived/keepalived-${masterIP}-master.conf <<EOF
global_defs {
    router_id master-${masterIP}
    enable_script_security
}
vrrp_script check-haproxy {
    script "/usr/bin/killall -0 haproxy"
    interval 5
    weight -30
    user root
}
vrrp_instance k8s {
    state MASTER
    priority 120
    dont_track_primary
    interface ${VIP_INTERFACE}
    virtual_router_id 88
    advert_int 3
    track_script {
        check-haproxy
    }
    virtual_ipaddress {
        ${APISERVER_VIP}
    }
}
EOF


for master_ip in ${MASTER_IP}
do
  echo "=========================================== ${master_ip} ==========================================="
  ssh root@${master_ip} "yum install -y keepalived psmisc"
  ssh root@${master_ip} "test -e ${KEEPALIVED_BIN_DIR} || mkdir -p ${KEEPALIVED_BIN_DIR}"
done

systemctl daemon-reload && systemctl enable keepalived && systemctl restart keepalived
scp ${K8S_DATA}/config/keepalived/keepalived-${masterIP}-master.conf root@${masterIP}:/etc/keepalived/keepalived.conf

for (( i=2; i <= ${MASTER}; i++ ))
do
cat  > ${K8S_DATA}/config/keepalived/keepalived-`echo ${MASTER_IP} | cut -d " " -f $i`-backup.conf <<EOF
global_defs {
    router_id backup-`echo ${MASTER_IP} | cut -d " " -f $i`
    enable_script_security
}
vrrp_script check-haproxy {
    script "/usr/bin/killall -0 haproxy"
    interval 5
    weight -30
    user root
}
vrrp_instance k8s {
    state BACKUP
    priority 110
    dont_track_primary
    interface ${VIP_INTERFACE}
    virtual_router_id 88
    advert_int 3
    track_script {
        check-haproxy
    }
    virtual_ipaddress {
        ${APISERVER_VIP}
    }
}
EOF
done


for (( i=2; i <= ${MASTER}; i++ ))
do
  scp ${K8S_DATA}/config/keepalived/keepalived-`echo ${MASTER_IP} | cut -d " " -f $i`-backup.conf root@`echo ${MASTER_IP} | cut -d " " -f $i`:/etc/keepalived/keepalived.conf
  sleep 1
  ssh root@`echo ${MASTER_IP} | cut -d " " -f $i` "systemctl daemon-reload;systemctl enable keepalived;systemctl restart keepalived"
done

for master_ip in ${MASTER_IP}
do
  echo "=========================================== ${master_ip} ==========================================="
  ssh root@${master_ip} "systemctl restart  keepalived"
done

for master_ip in ${MASTER_IP}
do
  echo "=========================================== ${master_ip} ==========================================="
  sleep 3
  ssh root@${master_ip} "systemctl status keepalived | grep Active"
done

sleep 3

for master_ip in ${MASTER_IP}
do
  echo "\n"
  echo -e "\033[33m --------->>>>>>> ${master_ip} PING VIP STATUS \033[0m"
  echo "\n"
  ssh root@${master_ip} "ping -c 2 ${APISERVER_VIP}"
done